﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HR.ProjectX.BLL.Messaging;
using HR.ProjectX.DAL.Repositories;
using HR.ProjectX.DAL.UnitOfWork;
using HR.ProjectX.BLL.ViewModels;
using HR.ProjectX.Models;
using HR.ProjectX.Models.Entities.Customers;

namespace HR.ProjectX.BLL.Services.CustomerService
{
    public class CustomerService : ICustomerService
    {
        private readonly IUnitOfWork _uow;
        private readonly ICustomerRepository _customerRepository;

        public CustomerService(IUnitOfWork uow,
                               ICustomerRepository customerRepository)
        {
            _uow = uow;
            _customerRepository = customerRepository;
        }

        public void CreateCustomer(CreateCustomerRequest request)
        {
            Customer customer = new Customer();
            customer.CustomerName = request.Name;
            customer.CustomerGender = request.Gender;
            customer.CustomerEmail = request.Email;
            customer.CustomerPhoneNumer = request.PhoneNumber;
            customer.CustomerAddress = request.Address;
            customer.CustomerTown = request.Town;
            customer.CustomerCountry = request.Country;

            ThrowExceptionIfCustomerIsInvalid(customer);

            _customerRepository.Add(customer);
            _uow.Commit();
        }

        public GetCustomerByResponse GetCustomerByEmail(GetCustomerByRequest request)
        {
            Customer customer = _customerRepository.FindCustomerByEmail(request.Email);
            CustomerView viewModel = new CustomerView();

            viewModel.CustomerName = customer.CustomerName;
            viewModel.CustomerGender = customer.CustomerGender;
            viewModel.CustomerEmail = customer.CustomerEmail;
            viewModel.CustomerPhoneNumer = customer.CustomerPhoneNumer;
            viewModel.CustomerAddress = customer.CustomerAddress;
            viewModel.CustomerTown = customer.CustomerTown;
            viewModel.CustomerCountry = customer.CustomerCountry;

            GetCustomerByResponse response = new GetCustomerByResponse();
            response.Customer = viewModel;

            return response;
        }

        private void ThrowExceptionIfCustomerIsInvalid(Customer customer)
        {
            if (customer.GetBrokenRules().Count() > 0)
            {
                StringBuilder brokenRules = new StringBuilder();
                brokenRules.AppendLine("There were problems saving the Booking:");
                foreach (BusinessRule businessRule in customer.GetBrokenRules())
                {
                    brokenRules.AppendLine(businessRule.Rule);
                }

                throw new CustomerInvalidException(brokenRules.ToString());
            }
        }
    }
}
